/**
 * 
 */
package com.pmsco.pms.core.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.pmsco.pms.core.dao.CategoryDao;
import com.pmsco.pms.core.domain.Category;
import com.pmsco.pms.util.JQGridBuildWhereClause;

/**
 * @author Long Tran
 *
 */
public class CategoryDaoImpl extends HibernateDaoSupport implements CategoryDao {

	public void saveOrUpdateCategory(Category category) {
		getHibernateTemplate().merge(category);
		getHibernateTemplate().flush();
	}

	public List<Category> listCategory(Category searchTemplate) {
		List<Category> ret = new ArrayList<Category>();
		ret = getHibernateTemplate().findByExample(searchTemplate);
		return ret;
	}

	public Category loadCategory(Category searchTemplate) {
		Category ret = null;
		List<Category> temp = new ArrayList<Category>();
		temp = getHibernateTemplate().findByExample(searchTemplate);
		if(temp != null && temp.size() == 1)
			ret = temp.get(0);
		return ret; 
	}
	
	public void deleteCategory(Category category) {
		getHibernateTemplate().delete(category);
		getHibernateTemplate().flush();
	}
	
	public List<Category> listCategory(String searchField, String searchString, String searchOper, String sidx, String sord, Integer page, Integer rows) {
		List<Category> ret = new ArrayList<Category>();
		Criteria crit = this.getSession().createCriteria(Category.class);
		if(searchOper != null && searchOper.length() > 0)
			crit.add(JQGridBuildWhereClause.getWhereClase(searchField, searchString, searchOper));
		if("desc".equalsIgnoreCase(sord))
			crit.addOrder(Order.desc(sidx));
		else
			crit.addOrder(Order.asc(sidx));
		crit.setFirstResult((page - 1) * rows);
		crit.setMaxResults(page * rows);
		ret = crit.list();
		return ret;
	}
	
	public Integer countListCategory(String searchField, String searchString, String searchOper) {
		Integer ret = new Integer(0);
		Criteria crit = this.getSession().createCriteria(Category.class);
		if(searchOper != null && searchOper.length() > 0)
			crit.add(JQGridBuildWhereClause.getWhereClase(searchField, searchString, searchOper));
		crit.setProjection(Projections.rowCount());
		ret = (Integer)crit.uniqueResult();
		return ret;
	}
	
	public Category getCategoryById(Long id) {
		List<Category> ret = findByProperty(Category.idField, id);
		if(ret != null && ret.size() > 0)
			return ret.get(0);
		else
			return null;
	}
	
	public List<Category> findByProperty(String propertyName, Object value) {
		try {
			String queryString = "from " + Category.className + " as model where model."
					+ propertyName + "= ? ";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
